/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package empcalculator;

import buildings.Shipyard;
import java.awt.Component;
import java.awt.Container;
import java.awt.FocusTraversalPolicy;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author steely
 */
public class EMPCalculatorFrame extends javax.swing.JFrame {

	/**
	 * Creates new form EMPCalculatorFrame
	 */
	public EMPCalculatorFrame() {
		initComponents();
		load();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jCBShip = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jTFAmount = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLInfo = new javax.swing.JLabel();
        jBCalculate = new javax.swing.JButton();
        jTFShipYardLevels = new javax.swing.JTextField();
        jCBNanorobots = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("EMP Calculator");
        setFocusCycleRoot(false);
        setResizable(false);

        jCBShip.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Choose a ship to build", "Fighter", "Unmanned Platform", "Unmanned Platform, Mod. 2", "Colonial Spaceship", "Engineering Spaceship", "Frigate", "Corvette" }));
        jCBShip.setToolTipText("What ship to build.");
        jCBShip.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCBShipActionPerformed(evt);
            }
        });

        jLabel1.setText("Amount to build");

        jTFAmount.setText("0");
        jTFAmount.setToolTipText("Amount of ships to build.");
        jTFAmount.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTFAmountKeyReleased(evt);
            }
        });

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setLabelFor(jTFShipYardLevels);
        jLabel2.setText("Shipyard Levels (comma seperate list)");
        jLabel2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        jLInfo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLInfo.setText(" ");
        jLInfo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(83, 83, 83)));

        jBCalculate.setText("Calculate");
        jBCalculate.setToolTipText("Calculate the amount of ships each shipyard should build.");
        jBCalculate.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jBCalculate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBCalculateActionPerformed(evt);
            }
        });

        jTFShipYardLevels.setText("10,11,12,13");
        jTFShipYardLevels.setToolTipText("Shipyard levels seperated by commas.");
        jTFShipYardLevels.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTFShipYardLevelsActionPerformed(evt);
            }
        });
        jTFShipYardLevels.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTFShipYardLevelsKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTFShipYardLevelsKeyTyped(evt);
            }
        });

        jCBNanorobots.setSelected(true);
        jCBNanorobots.setText("Nanorobots");
        jCBNanorobots.setToolTipText("Check if you have the nanorobot tech researched.");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTFShipYardLevels)
                    .addComponent(jLInfo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jCBShip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jTFAmount, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jCBNanorobots)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jBCalculate)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCBShip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jTFAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCBNanorobots))
                .addGap(18, 18, Short.MAX_VALUE)
                .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, Short.MAX_VALUE)
                .addComponent(jTFShipYardLevels, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, Short.MAX_VALUE)
                .addComponent(jBCalculate)
                .addGap(18, 18, Short.MAX_VALUE)
                .addComponent(jLInfo)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jCBShipActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCBShipActionPerformed
		// TODO add your handling code here:
    }//GEN-LAST:event_jCBShipActionPerformed

    private void jBCalculateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBCalculateActionPerformed
		// TODO add your handling code here:
		calculator();
    }//GEN-LAST:event_jBCalculateActionPerformed

    private void jTFShipYardLevelsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTFShipYardLevelsActionPerformed
		// TODO add your handling code here:
    }//GEN-LAST:event_jTFShipYardLevelsActionPerformed

    private void jTFShipYardLevelsKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTFShipYardLevelsKeyTyped
		// TODO add your handling code here:
    }//GEN-LAST:event_jTFShipYardLevelsKeyTyped

    private void jTFShipYardLevelsKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTFShipYardLevelsKeyReleased
		// TODO add your handling code here:
		if (evt.getKeyCode() == 10) {
			calculator();
		}
    }//GEN-LAST:event_jTFShipYardLevelsKeyReleased

    private void jTFAmountKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTFAmountKeyReleased
		// TODO add your handling code here:
		if (evt.getKeyCode() == 10) {
			calculator();
		}
    }//GEN-LAST:event_jTFAmountKeyReleased

	public class MyOwnFocusTraversalPolicy extends FocusTraversalPolicy {

		@Override
		public Component getComponentAfter(Container focusCycleRoot,
				Component aComponent) {
			if (aComponent.equals(jCBShip)) {
				return jTFAmount;
			} else if (aComponent.equals(jTFAmount)) {
				return jCBNanorobots;
			} else if (aComponent.equals(jCBNanorobots)) {
				return jTFShipYardLevels;
			} else if (aComponent.equals(jTFShipYardLevels)) {
				return jBCalculate;
			} else if (aComponent.equals(jBCalculate)) {
				return jCBShip;
			}
			return jCBShip;
		}

		@Override
		public Component getComponentBefore(Container focusCycleRoot,
				Component aComponent) {
			if (aComponent.equals(jCBShip)) {
				return jBCalculate;
			} else if (aComponent.equals(jTFAmount)) {
				return jCBShip;
			} else if (aComponent.equals(jCBNanorobots)) {
				return jTFAmount;
			} else if (aComponent.equals(jTFShipYardLevels)) {
				return jCBNanorobots;
			} else if (aComponent.equals(jBCalculate)) {
				return jTFShipYardLevels;
			}
			return jCBShip;
		}

		@Override
		public Component getDefaultComponent(Container focusCycleRoot) {
			return jCBShip;
		}

		@Override
		public Component getLastComponent(Container focusCycleRoot) {
			return jBCalculate;
		}

		@Override
		public Component getFirstComponent(Container focusCycleRoot) {
			return jCBShip;
		}
	}

	private void calculator() {
		String info;
		int ship;
		int amount;
		String[] shipyardLevels;
		Shipyard[] shipyards;

		Shipyard.setNanorobots(jCBNanorobots.isSelected());

		// get what ship to build
		ship = jCBShip.getSelectedIndex();
		if (ship == 0) {
			jLInfo.setText("ERROR: Please select what ship to build.");
			return;
		}

		// get amount of ships to build
		try {
			amount = Integer.parseInt(jTFAmount.getText());
		} catch (NumberFormatException e) {
			jLInfo.setText("ERROR: Amount is not a number.");
			return;
		}

		// get shipyard levels
		shipyardLevels = jTFShipYardLevels.getText().split(",");
		int length = shipyardLevels.length;
		shipyards = new Shipyard[length];
		for (int i = 0; i < length; i++) {
			int level;
			try {
				level = Integer.parseInt(shipyardLevels[i]);
			} catch (NumberFormatException e) {
				jLInfo.setText("ERROR: " + shipyardLevels[i] + " is not a number. Value " + String.valueOf(i + 1) + ".");
				return;
			}
			shipyards[i] = new Shipyard(level, ship);
		}

		backend.BuildShips.calculate(amount, shipyards);
		info = "";
		for (Shipyard shipyard : shipyards) {
			info = info.concat("," + String.valueOf(shipyard.getAmountToBuild()));
		}
		info = info.substring(1);
		jLInfo.setText(info);

		save();
	}

	private void save() {
		String saveDir = System.getProperty("user.home") + "/.EMPCalculator";
		PrintWriter printer = null;
		try {
			Files.createDirectory(Paths.get(saveDir));
		} catch (IOException ex) {
//			System.err.println(ex.getMessage());
		}
		try {
			printer = new PrintWriter(saveDir + "/save.txt");
			printer.printf("%d%n%s%n%s%n%s", jCBShip.getSelectedIndex(), jTFAmount.getText(), jCBNanorobots.isSelected(), jTFShipYardLevels.getText());
			printer.close();
		} catch (FileNotFoundException ex) {
			System.err.println(ex.getMessage());
			if (printer != null) {
				printer.close();
			}
		}
	}

	private void load() {
		FileReader fr;
		BufferedReader br = null;
		String[] lines;

		try {
			fr = new FileReader(System.getProperty("user.home") + "/.EMPCalculator/save.txt");
			br = new BufferedReader(fr);

			lines = new String[4];
			for (int i = 0; i < 4; i++) {
				lines[i] = br.readLine();
				if (lines[i] == null) {
					System.err.println("Save file doesn't have enough lines.");
					br.close();
					return;
				}
			}
			br.close();

			int ship = Integer.valueOf(lines[0]);
			if (ship <= 7 && ship >= 0) {
				jCBShip.setSelectedIndex(ship);
			} else {
				System.err.println("Line 1 of save file is not a number between 1 and 7.");
				return;
			}

			jTFAmount.setText(lines[1]);

			if (lines[2].equals("true")) {
				jCBNanorobots.setSelected(true);
			} else {
				jCBNanorobots.setSelected(false);
			}

			jTFShipYardLevels.setText(lines[3]);

		} catch (NumberFormatException ex) {
			System.err.println("Line 1 of the save file is not a number.");
		} catch (Exception ex) {
//			System.err.println(ex.getMessage());
			try {
				if (br != null) {
					br.close();
				}
			} catch (IOException ex1) {
				System.err.println(ex.getMessage());
			}
		}

	}

	private void corrupt() {
		System.err.println("Error in save file.");
	}

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
		 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(EMPCalculatorFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(EMPCalculatorFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(EMPCalculatorFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(EMPCalculatorFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		//</editor-fold>

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new EMPCalculatorFrame().setVisible(true);
			}
		});
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBCalculate;
    private javax.swing.JCheckBox jCBNanorobots;
    private javax.swing.JComboBox jCBShip;
    private javax.swing.JLabel jLInfo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTFAmount;
    private javax.swing.JTextField jTFShipYardLevels;
    // End of variables declaration//GEN-END:variables
}
